import Blockly from 'blockly/core'
import 'blockly/python_compressed'
import 'blockly/blockly_compressed'
import 'blockly/blocks_compressed'

Blockly.Blocks.ast_Raise = {
  init: function () {
    this.setInputsInline(true)
    this.setPreviousStatement(true, null)
    this.setNextStatement(true, null)
    this.setColour(230)
    this.exc_ = true
    this.cause_ = false

    this.appendDummyInput().appendField('raise')
    this.updateShape_()
  },
  updateShape_: function () {
    if (this.exc_ && !this.getInput('EXC')) {
      this.appendValueInput('EXC').setCheck(null)
    } else if (!this.exc_ && this.getInput('EXC')) {
      this.removeInput('EXC')
    }
    if (this.cause_ && !this.getInput('CAUSE')) {
      this.appendValueInput('CAUSE').setCheck(null).appendField('from')
    } else if (!this.cause_ && this.getInput('CAUSE')) {
      this.removeInput('CAUSE')
    }
    if (this.cause_ && this.exc_) {
      this.moveInputBefore('EXC', 'CAUSE')
    }
  },
  /**
   * Create XML to represent list inputs.
   * @return {!Element} XML storage element.
   * @this Blockly.Block
   */
  mutationToDom: function () {
    const container = document.createElement('mutation')
    container.setAttribute('exc', this.exc_)
    container.setAttribute('cause', this.cause_)
    return container
  },
  /**
   * Parse XML to restore the list inputs.
   * @param {!Element} xmlElement XML storage element.
   * @this Blockly.Block
   */
  domToMutation: function (xmlElement) {
    this.exc_ = xmlElement.getAttribute('exc') === 'true'
    this.cause_ = xmlElement.getAttribute('cause') === 'true'
    this.updateShape_()
  }
}

Blockly.Python.ast_Raise = function (block) {
  if (this.exc_) {
    const exc =
      Blockly.Python.valueToCode(block, 'EXC', Blockly.Python.ORDER_NONE) ||
      Blockly.Python.blank
    if (this.cause_) {
      const cause =
        Blockly.Python.valueToCode(block, 'CAUSE', Blockly.Python.ORDER_NONE) ||
        Blockly.Python.blank
      return 'raise ' + exc + ' from ' + cause + '\n'
    } else {
      return 'raise ' + exc + '\n'
    }
  } else {
    return 'raise' + '\n'
  }
}

export default Blockly
